<template>
  <div>
    <div class="operate_wrap flex" style="margin-left: 25px">
      <div class="flex-center g-flex flex-right">
        <el-select class="select" size="small" v-model="search.company" v-on:change="fixQueryA()" value-key="id" placeholder="选择公司" clearable>
          <el-option v-for="item in companyTree" :key="item.id" :label="item.name" :value="item">
          </el-option>
        </el-select>

        <el-date-picker v-model="search.week" type="week" class='no-clearable-picker' format="yyyy 第 WW 周" v-on:change="selectWeek()" placeholder="选择周">
        </el-date-picker>

        <el-button style="margin-left: 15px" type="primary" size="small" class="daochu buildButtonStyle" round @click="exportExcel">
          <i class="iconfont icon-daochu"></i>&nbsp;导出
        </el-button>
      </div>
      <div class="flex-row" style="padding-right: 20px;" v-if="!showButtonSecond">
        <el-button type="primary" size="small" class="add buildButtonStyle" @click="showButtonGroup" v-permission="permission.edit">编辑周报
        </el-button>
        <el-button type="primary" size="small" class="add buildButtonStyle" @click="showAddDialog" v-permission="permission.add">项目设置
        </el-button>
      </div>
      <div class="flex-row" style="padding-right: 20px;" v-if="showButtonSecond">
        <!--        <el-button-->
        <!--          type="primary"-->
        <!--          size="small"-->
        <!--          class="add buildButtonStyle"-->
        <!--          @click="buttonAction('submit')"-->
        <!--        >同步问题-->
        <!--        </el-button>-->
        <el-button type="primary" size="small" class="add buildButtonStyle" @click="buttonAction('confirm')">确定
        </el-button>
        <el-button type="primary" size="small" class="add buildButtonStyle" @click="buttonAction('cancel')">取消
        </el-button>
      </div>
    </div>
    <div class="list_wrap WholeScroll" style="padding: 20px;">
      <el-table class="project-management-info" :border="true" :row-class-name="tableRowStyleName" :cell-class-name="tableCellStyleName" :header-cell-class-name="tableHeaderCellStyleName" :stripe="true" ref="multipleTable" :span-method="objectSpanMethod" :data="list" tooltip-effect="dark" :height="tableHeight" style="width: 100%; font-family: PingFangSC-Regular; font-size: 14px">
        <el-table-column show-overflow-tooltip label="序号" type="index" fixed="left" width="50">
        </el-table-column>

        <el-table-column show-overflow-tooltip prop="projectName" align="left" fixed="left" width="180" label="项目名称">
          <template slot-scope="scope">
            <div class="row-new-line-css">
              <span>{{ scope.row.projectName }}</span>
              <div v-if="showButtonSecond">
                <i class="el-icon-caret-top" v-if="scope.$index != 0" @click="changeRowIndexEvent('top',scope.$index)"></i>
                <i class="el-icon-caret-bottom" v-if="scope.$index != list.length -1" @click="changeRowIndexEvent('bottom',scope.$index)"></i>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column label="前期工作开展情况" align="left" prop="workProgress">
          <template slot-scope="scope">
            <span class="tableRowSpan" v-show="!showButtonSecond">{{scope.row.workProgress}}</span>
            <el-input v-model="scope.row.workProgress" v-show="showButtonSecond" placeholder="请输入"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="存在问题" align="left" width="280">
          <template slot-scope="scope">
            <span class="tableRowSpan" v-show="!showButtonSecond">{{scope.row.problem}}</span>
            <el-input v-model="scope.row.problem" v-show="showButtonSecond" placeholder="请输入"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="共性问题" align="left" width="280">
          <template slot-scope="scope">
            <span class="tableRowSpan" v-show="!showButtonSecond">{{scope.row.commonProblems}}</span>
            <el-input v-model="scope.row.commonProblems" type="textarea" :autosize="{ minRows: 2, maxRows: 6 }" placeholder="" v-show="showButtonSecond" placeholder="请输入">
            </el-input>
          </template>
        </el-table-column>
        <el-table-column label="下一步工作计划" align="left" width="280">
          <template slot-scope="scope">
            <span class="tableRowSpan" v-show="!showButtonSecond">{{scope.row.nextPlan}}</span>
            <el-input v-model="scope.row.nextPlan" v-show="showButtonSecond" placeholder="请输入"></el-input>
          </template>
        </el-table-column>
        <el-table-column label="备 注" align="left" width="250">
          <template slot-scope="scope">
            <span class="tableRowSpan" v-show="!showButtonSecond">{{scope.row.mark}}</span>
            <el-input v-model="scope.row.mark" v-show="showButtonSecond" placeholder="请输入"></el-input>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <Detail :postDetail="postDetailData" @reloadList="getList(true)"></Detail>
  </div>
</template>

<script>
import Moment from 'moment'
import {
  tableRowStyleGol,
  tableCellStyleGol,
  tableHeaderCellStyleGol,
  doCreateObject,
} from '@/utils/publicFun'
import { getCompanyTree, getListForWeek, saveWeekReport, exportWeekExcel } from '@/api/buss/frontProject'
export default {
  name: 'weekReport',
  components: {
    Detail: require('./weekReport-detail/weekReport-detail').default
  },
  data() {
    return {
      permission: {
        add: ['100', '周报:add'],
        show: ['100', '周报:show'],
        edit: ['100', '周报:edit'],
        del: ['100', '周报:del'],
      },
      tableRowStyleName: tableRowStyleGol,
      tableCellStyleName: tableCellStyleGol,
      tableHeaderCellStyleName: tableHeaderCellStyleGol,
      tablePaginationPrev: '上一页',
      tablePaginationNext: '下一页',
      list: [],
      postDetailData: {
        show: false,
        type: 'build',
        typeNmae: '新增',
      },
      showButtonSecond: false,
      companyTree: [],
      spanArr: [],
      search: {
        subcontractName: '',
        pageIndex: 0,
        pageSize: 999,
        pageSum: 0,
        contractId: '',
        searchType: '', // 合同类型
        searchName: '', // 合同名称
        company: { children: [] },
        companyId: '',
        project: { children: [] },
        sectionId: '',
        projectId: '',
        week: this.getNowTime(),
        postWeek: '',
      },
    }
  },
  created() {
    this.getCompanyTree(() => this.getList())
    this.setWeekNum()
  },
  watch: {
    list: {
      handler(n, o) {
        this.getSpanArr(this.list)
      },
      immediate: true
    }
  },
  computed: {
    tableHeight: function () {
      return (window.innerHeight - 330) + 'px';
    }
  },
  methods: {
    exportExcel() {
      exportWeekExcel({ list: this.list }).then(res => {
        doCreateObject(res, '周报.xlsx')
      })
    },
    //合并行
    getSpanArr(data) {
      console.log(data, '==========')
      for (var i = 0; i < data.length; i++) {
        if (i === 0) {
          this.spanArr.push(1);
          this.pos = 0
        } else {
          // 判断当前元素与上一个元素是否相同
          if (data[i].commonProblems === data[i - 1].commonProblems) {
            this.spanArr[this.pos] += 1;
            this.spanArr.push(0);
          } else {
            this.spanArr.push(1);
            this.pos = i;
          }
        }
        console.log(this.spanArr)
      }
    },
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      if (columnIndex === 4) {
        const _row = this.spanArr[rowIndex];
        const _col = _row > 0 ? 1 : 0;
        return { // [0,0] 表示这一行不显示， [2,1]表示行的合并数
          rowspan: _row,
          colspan: _col
        }
      }
    },
    selectWeek() {
      this.setWeekNum()
      this.getList()
    },
    getNowTime() {
      return new Date();;
    },
    setWeekNum() {
      //注意，当返回值是中国标准时间的格式时使用moment.js的时候一定要加上.utcOffset(480)，用来转换时区
      this.search.postWeek = Moment(this.search.week).utcOffset(480).format("YYYY第WW周")
      console.log(this.search.postWeek)
    },
    fixQueryA() {
      this.getList()
    },
    getList() {
      this.list.splice(0, this.list.length)
      this.search.companyId = this.search.company.id
      getListForWeek(this.search).then((res) => {
        if (res.code === 200) {
          if (res.data.content.length > 0) {
            res.data.content.forEach((item, index) => {
              if (item.commonProblems == null) {
                item.commonProblems = ''
              }
            })
          }
          this.$set(this, 'list', res.data.content)

        } else {
          this.isLoading = false
          // this.$messageError(res.data.message)
        }
      })
        .catch((res) => {
          console.log('请求出现错误', res)
          this.isLoading = false
          // this.$messageError(this.$route.name + '提交详情-请求失败')
        })
    },
    getCompanyTree(callback) {
      getCompanyTree({}).then((res) => {
        // res.list.forEach(item=>{
        //   if('南阳方枣高速公路有限公司' === item.fullname){
        //     this.companyTree.push(item)
        //   }
        // })
        this.companyTree = res.list
        // this.search.company = res.list[0]
        this.search.company = this.companyTree[0]
        if (callback) callback()
      })
        .catch((res) => {
          console.log('请求出现错误', res)
          this.isLoading = false
          // this.$messageError(this.$route.name + '提交详情-请求失败')
        })
    },
    // 修改行的序列
    changeRowIndexEvent(type, index) {
      if (type == 'top') {
        this.upGo(this.list, index)
      } else {
        this.downGo(this.list, index)
      }
    },
    // 向上移动一格
    upGo(fieldData, index) {
      if (index != 0) {
        fieldData[index].num = fieldData[index].num - 1
        fieldData[index] = fieldData.splice(index - 1, 1, fieldData[index])[0];
        fieldData[index].num = fieldData[index].num + 1
      } else {
        fieldData.push(fieldData.shift());
      }
    },
    // 向下移动一格
    downGo(fieldData, index) {
      if (index != fieldData.length - 1) {
        fieldData[index].num = fieldData[index].num + 1
        fieldData[index] = fieldData.splice(index + 1, 1, fieldData[index])[0];
        fieldData[index].num = fieldData[index].num - 1
      } else {
        fieldData.unshift(fieldData.splice(index, 1)[0]);
      }
    },
    buttonAction(type) {
      switch (type) {
        case 'confirm':
          this.showButtonSecond = false
          //这边调，后台的存数据接口
          this.list.forEach((item, index) => {
            if (index != 0) {
              item.commonProblems = this.list[0].commonProblems
            }
          })
          saveWeekReport({ list: this.list })
            .then((res) => {
              this.getList()
              console.log('保存成功', res)
            })
            .catch((res) => {
              console.log('请求出现错误', res)
              this.isLoading = false
              // this.$messageError(this.$route.name + '提交详情-请求失败')
            })
          break;

        case 'cancel':
          this.showButtonSecond = false
          break
      }
    },
    showButtonGroup() {
      this.showButtonSecond = true
    },
    showAddDialog() {
      this.postDetailData = {
        show: true,
        type: 'build',
        typeName: '新增',
        companyId: this.search.company.id,
        week: this.search.week,
        postWeek: this.search.postWeek,
        list: this.list,
      }
    },
    // 切换列表
    paginationChange(index) {
      this.search.pageIndex = index - 1
      this.getList()
    },
  },
}
</script>

<style lang="scss" scoped>
.operate_wrap {
  .select {
    width: 250px;
    margin-right: 15px;
  }
}
.flex-row {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.row-new-line-css {
  display: flex;
  justify-content: space-between;
  align-items: center;
  span {
    overflow: hidden;
    text-overflow: ellipsis; //超出部分以省略号显示
    white-space: nowrap;
  }
  i {
    cursor: pointer;
  }
}
</style>
